<template>
  <div class="sound-main">
    <div class="sound-left">
      <div class="main">
        <div class="mainBox">
          <div class="mainBox-left">
            <div class="btns" v-show="flagShow">
              <!-- <el-button type="primary" @click="recOpen()">打开录音,请求权限</el-button> -->
              <!-- <el-button type="primary" @click="recClose()">关闭录音,释放资源</el-button> -->
              <el-button type="primary" :icon="Microphone" @click="recStart()">开始录音</el-button>
              <el-upload
                class="upload-demo contractCheck-main_upload"
                ref="uploadRef"
                :http-request="requestUpload"
                multiple
                :show-file-list="false"
                :file-list="fileUrls"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :on-remove="handleAvatarRemove"
              >
                <el-button style="margin-left: 12px" type="primary" :icon="Upload">上传录音</el-button>
              </el-upload>
              <el-button style="margin-left: 12px" type="danger" @click="clearFiles()">清空</el-button>
            </div>
            <el-button style="right: 0" type="primary" icon="Document" @click="logout" class="export-btn"> 退出登录 </el-button>
          </div>
          <div class="control-content">
            <div class="main-left">
              <div class="loader" v-if="!flagShow && !pauseFlag"></div>
              <div style="height: 20px; width: 88px" class="ctrlProcessWave"></div>
              <div v-show="durationTxt != '0'" class="ctrlProcessT" style="line-height: 40px; position: relative">{{ `${durationTxt}` }}</div>
            </div>
            <div class="main-right">
              <!-- 根据 pauseFlag 的值来显示不同的按钮 -->
              <el-tooltip class="box-item" effect="dark" :content="pauseFlag ? '继续录音' : '暂停录音'" placement="top">
                <div v-show="!flagShow">
                  <!-- 如果暂停，则显示继续录音图标 -->
                  <PlayOne
                    class="icon_style"
                    v-if="pauseFlag"
                    style="cursor: pointer"
                    theme="outline"
                    size="24"
                    fill="#000000"
                    @click="recResume()"
                  />
                  <!-- 如果未暂停，则显示暂停图标 -->
                  <Pause class="icon_style" v-else style="cursor: pointer" theme="outline" size="24" fill="#000000" @click="recPause()" />
                </div>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="结束录音" placement="top">
                <div v-show="!flagShow">
                  <power class="icon_style" style="cursor: pointer" theme="outline" size="24" fill="#e35734" @click="recStop()" />
                </div>
              </el-tooltip>
              <el-button v-show="recLogLast && flagShow" type="primary" :icon="Download" @click="recDownLast()">下载录音</el-button>
            </div>
          </div>
          <div v-if="recLogLast"><audio style="width: 100%; margin-top: 12px" ref="LogAudioPlayer"></audio></div>
        </div>
      </div>

      <div class="main">
        <el-input type="textarea" :autosize="{ minRows: 23, maxRows: 23 }" placeholder="展示结果" v-model="text" readonly> </el-input>
      </div>
    </div>
    <div class="sound-right">
      <div class="mainBox mainBox-right">
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:aiTask:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:aiTask:export']">导出</el-button>
          </el-col>
        </el-row> -->
        <div style="margin-bottom: 10px; font-weight: 600; color: #515a6e">任务列表</div>
        <el-table v-loading="loading" :data="aiTaskList" @selection-change="handleSelectionChange">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column type="index" label="编号" width="55" align="center" />
          <!-- <el-table-column label="创建任务的用户编号" align="center" prop="userId" /> -->
          <!-- <el-table-column label="任务类型" align="center" prop="taskType">
            <template #default="scope">
              <dict-tag :options="ai_task_type" :value="scope.row.taskType" />
            </template>
          </el-table-column> -->
          <el-table-column label="文件名称" align="center" prop="taskName" />
          <!-- <el-table-column label="任务内容" align="center" prop="taskContent" /> -->
          <el-table-column label="任务状态" align="center" prop="taskStatus">
            <template #default="scope">
              <dict-tag :options="ai_task_status" :value="scope.row.taskStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="vieRes(scope.row.taskContent)" :disabled="scope.row.taskStatus == 0 ? true : false"
                >查看结果</el-button
              >
              <el-button link type="primary" @click="viewMindMap(scope.row)" :disabled="scope.row.taskStatus == 0 ? true : false">思维导图</el-button>
              <!-- <el-button link type="primary" @click="handleDelete(scope.row)">下载</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>
    <el-dialog v-model="showOpenRec" title="打开网页录音权限" width="30%">
      <el-button type="primary" @click="recOpen('1')">打开录音,请求权限</el-button>
      <el-button @click="showOpenRec = false">取消</el-button>
    </el-dialog>

    <el-dialog v-model="openMindMax" :title="mindBoxName" width="80%" @close="closeMindBox">
      <div style="padding: 20px 0">
        <MindMap ref="mindMapRef" :mindData="mindData" :showMindMap="showMindMap" />
      </div>
    </el-dialog>
    <!-- <div>
    <div class="main">
      <slot name="top"></slot>

      <div class="mainBox">
        <div class="btns">
          <div style="margin-bottom: 20px">
            <el-button type="primary" @click="recOpen()">打开录音,请求权限</el-button>
            <el-button type="primary" @click="recClose()">关闭录音,释放资源</el-button>
          </div>

          <el-button v-show="flagShow" type="primary" :icon="Microphone" @click="recStart()">录制</el-button>
          <el-button v-show="!flagShow" style="margin-left: 0" type="danger" :icon="Mute" @click="recStop()">停止</el-button>

          <el-button :disabled="!flagShow && !pauseFlag ? false : true" type="info" :icon="VideoPause" @click="recPause()">暂停</el-button>
          <el-button :disabled="!flagShow && pauseFlag ? false : true" type="success" :icon="VideoPlay" @click="recResume()">继续</el-button>
          <el-button type="primary" :icon="Headset" @click="recPlayLast()">播放</el-button>

          <el-button type="primary" :icon="Upload" @click="recUploadLast()">上传录音</el-button>
          <el-button type="primary" :icon="Download" @click="recDownLast()">本地下载</el-button>
        </div>
      </div>

      <div class="mainBox">
        <div style="height: 100px; width: 100%; border: 1px solid #ccc; box-sizing: border-box; vertical-align: bottom" class="ctrlProcessWave"></div>

        <div style="height: 40px; width: 100%; text-align: center; background: #999; position: relative; vertical-align: bottom">
          <div class="ctrlProcessX" style="height: 40px; background: #0b1; position: absolute" :style="{ width: powerLevel + '%' }"></div>
          <div class="ctrlProcessT" style="line-height: 40px; position: relative">{{ `${durationTxt}` }}</div>
        </div>
      </div>

      <div class="mainBox">
        <AUDIO ref="LogAudioPlayer" style="width: 100%"></AUDIO>

        <div class="mainLog">
          <div v-for="obj in logs" :key="obj.idx">
            <div :style="{ color: obj.color == 1 ? 'red' : obj.color == 2 ? 'green' : obj.color }">
              <span v-once>[{{ getTime() }}]</span><span v-html="obj.msg" />

              <template v-if="obj.res">
                {{ intp(obj.res.rec.set.bitRate, 3) }}kbps {{ intp(obj.res.rec.set.sampleRate, 5) }}hz 编码{{ intp(obj.res.blob.size, 6) }}b [{{
                  obj.res.rec.set.type
                }}]{{ obj.res.durationTxt }}ms

                <button @click="recdown(obj.idx)">下载</button>
                <button @click="recplay(obj.idx)">播放</button>

                <span v-html="obj.playMsg"></span>
                <span v-if="obj.down">
                  <span style="color: red">{{ obj.down }}</span>

                  没弹下载？试一下链接或复制文本<button @click="recdown64(obj.idx)">生成Base64文本</button>

                  <textarea v-if="obj.down64Val" v-model="obj.down64Val"></textarea>
                </span>
              </template>
            </div>
          </div>
        </div>
      </div>

      <slot name="bottom"></slot>
    </div>

    <div class="main">
      <div class="mainBox">
        <div class="btns">
          <el-button type="danger" @click="clearFiles()">清空</el-button>
        </div>
      </div>

      <el-upload
        class="upload-demo contractCheck-main_upload"
        ref="uploadRef"
        drag
        :http-request="requestUpload"
        multiple
        show-file-list
        :file-list="fileUrls"
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :on-remove="handleAvatarRemove"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <div>
        <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 30 }" placeholder="展示结果" v-model="text" readonly> </el-input>
      </div>
    </div>
  </div> -->
  </div>
</template>

<script setup lang="ts">
//必须引入的核心
import Recorder from 'recorder-core';

//引入mp3格式支持文件；如果需要多个格式支持，把这些格式的编码引擎js文件放到后面统统引入进来即可
import 'recorder-core/src/engine/mp3';
import 'recorder-core/src/engine/mp3-engine';
//录制wav格式的用这一句就行
import 'recorder-core/src/engine/wav';

//可选的插件支持项，这个是波形可视化插件
import 'recorder-core/src/extensions/waveview';

//ts import 提示：npm包内已自带了.d.ts声明文件（不过是any类型）
import { sendMessage, listAiTask, getAiTask, addAiTask, updateAiTask, delAiTask, getMindMap } from '@/api/aiManage/sound/index';
import { useNoticeStore } from '@/store/modules/notice';
import type { UploadInstance } from 'element-plus';
import { Microphone, Mute, VideoPause, VideoPlay, Headset, Upload, Download, Document } from '@element-plus/icons-vue';
import request from '@/utils/request';
import { globalHeaders } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import { Pause, PlayOne, Power } from '@icon-park/vue-next';
import '@icon-park/vue-next/styles/index.css'; // 导入图标样式
import { onBeforeUnmount, onUnmounted } from 'vue';
import MindMap from '@/components/MindMap/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ai_task_status, ai_task_type } = toRefs<any>(proxy?.useDict('ai_task_status', 'ai_task_type'));
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const noticeStore = storeToRefs(useNoticeStore());
const fileUrls = ref([]);
const text = ref('');
const headers = ref(globalHeaders());
const uploadImgUrl = baseUrl + '/system/oss/upload'; // 上传的图片服务器地址
const uploadRef = ref<UploadInstance>();
const flagShow = ref(true);
const pauseFlag = ref(false);
const logs = ref([]);
const powerLevel = ref(0);
const durationTxt = ref('0');
const rec = ref();
const wave = ref();
const duration = ref(0);
const type = ref('wav');
const bitRate = ref(16);
const sampleRate = ref(16000);
const recLogLast = ref();
const LogAudioPlayer = ref();
const userStore = useUserStore();
const userId = ref(userStore.userId);
const showOpenRec = ref(false);
/* 表格 */
const loading = ref(false);
const aiTaskList = ref([]);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const initFormData = {
  taskId: undefined,
  userId: undefined,
  taskType: undefined,
  taskName: undefined,
  taskContent: undefined,
  taskStatus: undefined
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    userId: userId.value.toString(),
    taskType: undefined,
    taskName: undefined,
    taskContent: undefined,
    taskStatus: undefined,
    params: {}
  },
  rules: {
    taskId: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
/* 思维导图 */
const showMindMap = ref(false);
const mindBoxName = ref('思维导图');
const openMindMax = ref(false);
const mindData = ref();
const mindMapRef = ref(null);
const router = useRouter();

const recOpen = (isDialog?) => {
  //创建录音对象
  rec.value = Recorder({
    type: type.value, //录音格式，可以换成wav等其他格式
    bitRate: +bitRate.value,
    sampleRate: sampleRate.value, //录音的采样率，越大细节越丰富越细腻
    onProcess: (buffers, currentPowerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) => {
      //录音实时回调，大约1秒调用12次本回调
      //可实时绘制波形，实时上传（发送）数据
      duration.value = bufferDuration;
      durationTxt.value = formatMs(bufferDuration, 1);
      powerLevel.value = currentPowerLevel;
      if (wave.value) {
        wave.value.input(buffers[buffers.length - 1], currentPowerLevel, bufferSampleRate);
      }
    }
  });

  //打开录音，获得权限
  rec.value.open(
    () => {
      // reclog('已打开:' + type.value + ' ' + sampleRate.value + 'hz ' + bitRate.value + 'kbps', 2);
      // proxy.$modal.msgSuccess('已打开:' + type.value + ' ' + sampleRate.value + 'hz ' + bitRate.value + 'kbps');
      console.log('已打开:' + type.value + '' + sampleRate.value + 'hz' + bitRate.value + 'kbps');
      if (isDialog) {
        showOpenRec.value = false;
        proxy.$modal.msgSuccess('已打开:' + type.value + ' ' + sampleRate.value + 'hz ' + bitRate.value + 'kbps');
      }
      // 创建波形可视化对象
      wave.value = Recorder.WaveView({ elem: '.ctrlProcessWave' });
    },
    (msg, isUserNotAllow) => {
      // 用户拒绝了录音权限，或者浏览器不支持录音
      const errorMessage = (isUserNotAllow ? 'UserNotAllow，' : '') + '打开失败：' + msg;
      // reclog(errorMessage, 1);
      proxy.$modal.msgError(errorMessage);
      if (isDialog) {
        showOpenRec.value = false;
        proxy.$modal.msgError(errorMessage);
      }
    }
  );
};

const recClose = () => {
  if (rec.value) {
    rec.value.close();
    rec.value = null; // 确保关闭后将其置为 null
    flagShow.value = true;
    // reclog('已关闭');
    // proxy.$modal.msgSuccess('已关闭录音权限');
    console.log('已关闭录音权限');
  } else {
    // reclog('未打开录音', 1);
    proxy.$modal.msgError('未打开录音，请打开录音权限');
    showOpenRec.value = true;
  }
};

const recStart = () => {
  if (!rec.value || !Recorder.IsOpen()) {
    proxy.$modal.msgError('未打开录音，请打开录音权限');
    showOpenRec.value = true;
    // reclog('未打开录音', 1);
    return;
  }
  const waveElement = document.querySelector('.ctrlProcessWave');
  if (waveElement instanceof HTMLElement) {
    waveElement.style.display = 'block';
  }
  recLogLast.value = undefined;
  rec.value.start();
  flagShow.value = false;
  var set = rec.value.set;
  proxy.$modal.msgSuccess('已打开:' + set.type + '' + set.sampleRate + 'hz' + set.bitRate + 'kbps');
  // reclog('录制中：' + set.type + ' ' + set.sampleRate + 'hz ' + set.bitRate + 'kbps');
};

const recStop = async () => {
  // 检查 rec.value 是否存在且录音已打开
  if (rec.value && Recorder.IsOpen()) {
    flagShow.value = true;
    rec.value.stop(
      async (blob, duration) => {
        await reclog('已录制:', '', {
          blob: blob,
          duration: duration,
          durationTxt: formatMs(duration),
          rec: rec.value
        });
        proxy.$modal.msgSuccess('已录制成功！！！');
        await recplay(recLogLast.value.idx);
        await recUploadLast();
      },
      (s) => {
        proxy.$modal.msgError('录制失败：' + s);
        // reclog('录音失败：' + s, 1);
      }
    );
    // recClose();
  } else {
    proxy.$modal.msgError('未打开录音，请打开录音权限');
    showOpenRec.value = true;
    // reclog('未打开录音', 1);
  }
};

const recPause = () => {
  if (rec.value && Recorder.IsOpen()) {
    rec.value.pause();
    pauseFlag.value = true;
  } else {
    proxy.$modal.msgError('未打开录音，请打开录音权限');
    showOpenRec.value = true;
    // reclog('未打开录音', 1);
  }
};

const recResume = () => {
  if (rec.value && Recorder.IsOpen()) {
    rec.value.resume();
    pauseFlag.value = false;
  } else {
    proxy.$modal.msgError('未打开录音，请打开录音权限');
    showOpenRec.value = true;
    // reclog('未打开录音', 1);
  }
};

const recPlayLast = () => {
  if (!recLogLast.value) {
    proxy.$modal.msgError('请先录音，然后停止后再播放');
    // reclog('请先录音，然后停止后再播放', 1);
    return;
  }
  recplay(recLogLast.value.idx);
};

const recplay = (idx) => {
  var o = logs.value[logs.value.length - idx - 1];
  o.play = (o.play || 0) + 1;
  var logmsg = function (msg) {
    o.playMsg = '<span style="color:green">' + o.play + '</span> ' + getTime() + ' ' + msg;
  };
  logmsg('');

  var audio = LogAudioPlayer.value;
  audio.controls = true;
  if (!(audio.ended || audio.paused)) {
    audio.pause();
  }
  audio.onerror = function (e) {
    proxy.$modal.msgError('播放失败[' + audio.error.code + ']' + audio.error.message);
    // logmsg('<span style="color:red">播放失败[' + audio.error.code + ']' + audio.error.message + '</span>');
  };
  // eslint-disable-next-line no-undef
  audio.src = (window.URL || webkitURL).createObjectURL(o.res.blob);
  // audio.play();
};

const recUploadLast = async () => {
  if (!recLogLast.value) {
    proxy.$modal.msgError('请先录音，然后停止后再上传');
    // reclog('请先录音，然后停止后再上传', 1);
    return;
  }
  var blob = recLogLast.value.res.blob;
  console.log('啊啊啊：', blob);
  text.value = '';
  /***方式二：使用FormData用multipart/form-data表单上传文件***/
  var form = new FormData();
  form.append('file', blob, 'recorder.wav'); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
  form.append('sessionKey', userId.value.toString()); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
  form.append('topic', 'soundWebSocket');
  //...其他表单参数
  await sendMessage(form);
  await getList();
};

const recDownLast = () => {
  if (!recLogLast.value) {
    proxy.$modal.msgError('请先录音，然后停止后再下载');
    // reclog('请先录音，然后停止后再下载', 1);
    return;
  }
  recdown(recLogLast.value.idx);
};

const recdown = (idx) => {
  var o = logs.value[logs.value.length - idx - 1];
  o.down = (o.down || 0) + 1;

  o = o.res;
  var name =
    'rec-' +
    o.duration +
    'ms-' +
    (o.rec.set.bitRate || '-') +
    'kbps-' +
    (o.rec.set.sampleRate || '-') +
    'hz.' +
    (o.rec.set.type || (/\w+$/.exec(o.blob.type) || [])[0] || 'unknown');
  var downA = document.createElement('A') as HTMLAnchorElement;
  // eslint-disable-next-line no-undef
  downA.href = (window.URL || webkitURL).createObjectURL(o.blob);
  downA.download = name;
  downA.click();
};

const recdown64 = (idx) => {
  var o = logs.value[logs.value.length - idx - 1];
  var reader = new FileReader();
  reader.onloadend = function () {
    o.down64Val = reader.result;
  };
  reader.readAsDataURL(o.res.blob);
};

const getTime = () => {
  var now = new Date();
  var t = ('0' + now.getHours()).substr(-2) + ':' + ('0' + now.getMinutes()).substr(-2) + ':' + ('0' + now.getSeconds()).substr(-2);
  return t;
};

const formatMs = (ms, all?) => {
  var ss = ms % 1000;
  ms = (ms - ss) / 1000;
  var s = ms % 60;
  ms = (ms - s) / 60;
  var m = ms % 60;
  ms = (ms - m) / 60;
  var h = ms;
  var t =
    (h ? `${h}:` : '00:') + (all || h + m ? `${String(m).padStart(2, '0')}:` : '00:') + (all || h + m + s ? `${String(s).padStart(2, '0')}″` : '00″');
  /* var t =
    (h ? `${h}:` : '00:') +
    (all || h + m ? `${String(m).padStart(2, '0')}:` : '00:') +
    (all || h + m + s ? `${String(s).padStart(2, '0')}″` : '00″') +
    String(ss).padStart(3, '0'); */
  return t;
};

const intp = (s, len) => {
  s = s == null ? '-' : s + '';
  if (s.length >= len) return s;
  return ('_______' + s).substr(-len);
};

const reclog = (msg, color?, res?) => {
  var obj = {
    idx: logs.value.length,
    msg: msg,
    color: color,
    res: res,
    playMsg: '',
    down: 0,
    down64Val: ''
  };
  if (res && res.blob) {
    recLogLast.value = obj;
  }
  logs.value.splice(0, 0, obj);
};

const clearFiles = () => {
  uploadRef.value.clearFiles(); // 调用 clearFiles 方法清空文件列表
  text.value = '';
  fileUrls.value = [];
  recLogLast.value = undefined;
  durationTxt.value = '0';
  const waveElement = document.querySelector('.ctrlProcessWave');
  if (waveElement instanceof HTMLElement) {
    waveElement.style.display = 'none';
  }
};

const requestUpload = async (uploadFile: any) => {
  // 上传文件
  text.value = '';
  const formData = new FormData();
  formData.append('file', uploadFile.file);
  formData.append('sessionKey', userId.value.toString());
  formData.append('topic', 'soundWebSocket');
  await sendMessage(formData);
  await getList();
};

const beforeAvatarUpload = (file: any) => {
  proxy.$modal.loading('上传录音中...');
  return true;
};

const handleAvatarSuccess = (res: any, file: any, fileList: any) => {
  proxy.$modal.closeLoading();
  recLogLast.value = undefined;
  const waveElement = document.querySelector('.ctrlProcessWave');
  if (waveElement instanceof HTMLElement) {
    waveElement.style.display = 'none';
  }
  durationTxt.value = '0';
  /* text.value = res;
  if (res.code == 200) {
    fileUrls.value = fileList;
    proxy.$modal.closeLoading();
  } else {
    proxy.$modal.msgError(res.msg);
    proxy.$modal.closeLoading();
  } */
};

const handleAvatarError = (err: any) => {
  proxy.$modal.closeLoading();
};

const handleAvatarRemove = (file: any, fileList: any) => {
  fileUrls.value = fileList;
};

/* 表格操作 */
/** 查询ai任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAiTask(queryParams.value);
  aiTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除ai任务编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await delAiTask(_taskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/aiTask/export',
    {
      ...queryParams.value
    },
    `任务列表_${new Date().getTime()}.xlsx`
  );
};

/** 查看结果 */
const vieRes = (val) => {
  text.value = val;
};

/** 展示思维导图 */
const viewMindMap = (val) => {
  openMindMax.value = true;
  showMindMap.value = true;
  mindBoxName.value = val.taskName ? val.taskName + '思维导图' : '思维导图';
  getMindMap(val.taskId).then((res) => {
    if (res.code == 200) {
      mindData.value = JSON.parse(res.msg);
      mindMapRef.value.updateMindMap(mindData.value);
    } else {
      proxy.$modal.msgError(res.msg);
    }
  });
};

const closeMindBox = () => {
  openMindMax.value = false;
  mindMapRef.value.destroyMindMap();
  showMindMap.value = false;
  mindBoxName.value = '思维导图';
  mindData.value = null;
};

// 检查 taskStatus 并设置定时器
let intervalId = null;
const checkTaskStatusAndSetInterval = () => {
  intervalId = setInterval(() => {
    const hasStatusZero = aiTaskList.value.some((item) => item.taskStatus == '0');
    if (hasStatusZero) {
      getList();
    }
  }, 5000);
};

const logout = async () => {
  await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  let loginType = userStore.loginType ? JSON.parse(JSON.stringify(userStore.loginType)) : '';
  userStore.logout().then(() => {
    if (loginType) {
      router.replace({
        path: '/creativeProjectsLogin',
        query: {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      });
    } else {
      router.replace({
        path: '/login',
        query: {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      });
    }
    loginType = '';
  });
};

onBeforeUnmount(() => {
  recClose();
  if (rec.value) {
    rec.value.close();
    rec.value = null; // 确保关闭后将其置为 null
    // reclog('已关闭录音，离开页面');
  }
});

onMounted(async () => {
  await recOpen();
  await getList();
  await checkTaskStatusAndSetInterval();
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style lang="scss" scoped>
body {
  word-wrap: break-word;
  background: #f5f5f5 center top no-repeat;
  background-size: auto 680px;
}

pre {
  white-space: pre-wrap;
}

a {
  text-decoration: none;
  color: #06c;
}

a:hover {
  color: #f00;
}

.main {
  max-width: 700px;
  margin: 0 auto;
  padding-bottom: 80px;
}

.mainBox {
  margin-top: 12px;
  padding: 12px 20px;
  border-radius: 6px;
  background: #fff;
  --border: 1px solid #0b1;
  box-shadow: 2px 2px 3px #aaa;
}

.mainBox-left {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.mainBox-right {
  height: 80vh;
}

::v-deep .mainBox-right .el-table__body-wrapper > .el-scrollbar {
  height: calc(80vh - 200px) !important;
  overflow-y: auto !important;
}

.pd {
  padding: 0 0 6px 0;
}
.lb {
  display: inline-block;
  vertical-align: middle;
  background: #00940e;
  color: #fff;
  font-size: 14px;
  padding: 2px 8px;
  border-radius: 99px;
}
.el-upload-dragger,
.el-upload {
  width: 100%;
}
.sound-main {
  padding: 0 20px;
  min-height: calc(100vh - 84px);
  background-color: #f0f4f9; //浅紫
  display: flex;
  flex-direction: row;
}

.sound-left,
.sound-right {
  flex: 1;
}

.sound-left {
  margin-right: 20px;
}

.btns {
  display: flex;
  flex-direction: row;
}

.control-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.main-left,
.main-right {
  width: auto;
  height: 100%;
  display: flex;
  align-items: center;
}

.ctrlProcessT {
  display: flex;
  align-items: center;
  justify-content: end;
  margin: 0 10px 0 12px;
  width: 55px;
  font-size: 12px;
  line-height: 1;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  color: #0009;
}

.icon_style {
  margin-left: 12px;
  padding: 4px;
}

.icon_style:hover {
  background: rgb(0, 0, 0, 0.06);
  border-radius: 7px;
}

.loader {
  min-width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ff4754;
  animation: 1.5s pulse infinite ease-in-out;
  margin-right: 13px;
  display: block; /* 默认隐藏 */
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 #ff4754;
  }

  100% {
    box-shadow: 0 0 0 5px rgba(255, 71, 84, 0); // 完全透明
  }
}
</style>
